const assert = require("assert");
var jwt = require("jsonwebtoken");
const { isNumber } = require("util");
module.exports = class extends think.Controller {
  static get _REST() {
    return true;
  }

  constructor(ctx) {
    super(ctx);
    this.resource = this.getResource();
    this.id = this.getId();

    assert(think.isFunction(this.model), "this.model must be a function");
    this.modelInstance = this.model(this.resource, "maya");
  }
  async __before() {
    try {
        this.userinfo = await this.analysisToken(this.ctx.header.token);
      } catch (e) {}
  }
  /**
   * get resource
   * @return {String} [resource name]
   */
  getResource() {
    return this.ctx.controller.split("/").pop();
  }
  getId() {
    const id = this.get("id");
    if (id && (think.isString(id) || think.isNumber(id))) {
      return id;
    }
    const last = this.ctx.path.split("/").slice(-1)[0];
    if (last !== this.resource) {
      return last;
    }
    return "";
  }
  async getAction() {
    let data;
    let cg = this.get();

    if (this.id) {
      const pk = this.modelInstance.pk;
      data = await this.modelInstance
        .where({
          [pk]: this.id,
        })
        .find();
      return this.success(data);
    }
    if (cg.page) {
      let obj = {};
      for (let key in cg) {
        if (
          key != "page" &&
          key != "addTime" &&
          key != "field" &&
          key != "pageSize"
        ) {
          let jhse = cg[key].split(",");
          let jhbser = [];
          jhse.map((a) => {
            if (key == "state") {
              jhbser.push(a);
            } else {
              jhbser.push(`%${a}%`);
            }
          });
          obj[key] = ["like", jhbser];
        }
        if (key == "addTime") {
          let jhse = cg[key].split(",");
          obj.addTime = {
            ">": this.sjhbert(jhse[0], 0),
            "<": this.sjhbert(jhse[1], 1),
          };
        }
      }

      const field = this.get("field");
      obj.openid = this.userinfo.openid
      data = await this.modelInstance
        .join({
          table: "dxgjadmin.wxcharUser",
          join: "left", //join 方式，有 left, right, inner 3 种方式
          as: "b",
          on: ["fenxiangList.openid", "openid"],
        })
        
        .field("fenxiangList.*,b.headPortrait,b.nickname,b.name")
        .page(cg.page, parseInt(cg.pageSize) || 10)
        .order("paixu DESC")
        .countSelect();
        data.data.map(a=>{
          try{
            a.imgList = a.imgList.split(",")
          }catch(e){
            
          }
        })

        for(let i=0;i<data.data.length;i++){
          data.data[i].dzsl=await this.diosersd(data.data[i].id)
          data.data[i].sc=await this.isdianzan(data.data[i].id) 
        }
        
      return this.success(data);
    }
    if (cg) {
      let obj = {};
      for (let key in cg) {
        if (key != "page") {
          let jhse = cg[key].split(",");
          let jhbser = [];

          jhse.map((a) => {
            if (key != "sxname") {
              try {
                a = parseInt(a);
                jhbser.push(a);
              } catch (e) {
                jhbser.push(`%${a}%`);
              }
            }
            if (key == "sxname") {
              jhbser.push(`%${a}%`);
            }
          });
          obj[key] = ["like", jhbser];
        }
      }
      data = await this.modelInstance.where(obj).order("id DESC").select();
      return this.success(data);
    }
    data = await this.modelInstance.select();
    return this.success(data);
  }
  async  diosersd(jid){
    const dianzanlist = this.model("dianzanlist", "maya");
    const njsdr = await  dianzanlist.where({jid}).count('id');
    return njsdr
  }
  async  isdianzan(jid){
    const dianzanlist = this.model("dianzanlist", "maya");
    const dfrty = await  dianzanlist.where({openid:this.userinfo.openid,jid}).field("jid").find()
    return dfrty.jid
  }
  /**
   * put resource
   * @return {Promise} []
   */
  async postAction() {
    const pk = this.modelInstance.pk;
    const data = this.post();
    delete data[pk];
    if (think.isEmpty(data)) {
      return this.fail("data is empty");
    }
    let insertId = "";
    let msgText = "添加成功2",
      code = 0;
    data.addTime = this.timeCycle(new Date().getTime());
    data.openid = this.userinfo.openid

    
    const jxxrt =  new Date().getTime()+(data.djssjc*1000)
    const nxcxfdt =  this.timeCycle(jxxrt)
    data.riqi = nxcxfdt.split(" ")[0]
    data.time =nxcxfdt.split(" ")[1]
    const number = await this.modelInstance.max("paixu");
    data.paixu = number + 1;
    try {
      data.publisher = this.tokensd.id;
    } catch (e) {}
    if (data.dateManufacture) {
      data.dateManufacture = this.timeCycle(data.dateManufacture);
    }
    if (data.thenAdd) {
      let duix = {};
      duix[data.thenAdd] = data[data.thenAdd];
      insertId = await this.modelInstance.thenAdd(data, duix);
      if (insertId.type == "exist") {
        msgText = data.errmsg || "有重复的数据";
        code = -1;
      }
    } else {
      insertId = await this.modelInstance.add(data);
    }

    if (code == -1) {
      return this.fail(code, msgText);
    } else {
      return this.success({
        msg: msgText,
        insertId,
      });
    }
  }
  /**
   * delete resource
   * @return {Promise} []
   */
  async deleteAction() {
    if (!this.id) {
      return this.fail("params error");
    }
    const idsList = this.get("id").split(",");
    let cs = this.id;
    if (idsList.length > 0) {
      cs = idsList;
    }
    const pk = this.modelInstance.pk;
    const rows = await this.modelInstance
      .where({
        [pk]: cs,
      })
      .delete();
    return this.success({
      affectedRows: rows,
    });
  }
  /**
   * update resource
   * @return {Promise} []
   */
  async putAction() {
    const pk = this.modelInstance.pk;
    const data = this.post();
    // data.addTime = this.timeCycle(new Date().getTime());

    try {
      data.publisher = this.tokensd.id;
    } catch (e) {}
    if (data.dateManufacture) {
      data.dateManufacture = this.timeCycle(data.dateManufacture);
    }
    data[pk] = this.post("id"); // rewrite data[pk] forbidden data[pk] !== this.id
    if (think.isEmpty(data)) {
      return this.fail("data is empty");
    }
    const rows = await this.modelInstance
      .where({
        [pk]: this.post("id"),
      })
      .update(data);
    return this.success({
      affectedRows: rows,
    });
  }
  /**
   * @param t格式化的时间戳
   * @return 2021-12-12 12:12:12 如果t没传返回当前的时间
   **/
  timeCycle(t) {
    let time = new Date();
    if (t) {
      time = new Date(t);
    }
    let Year = time.getFullYear(),
      Month = time.getMonth() + 1,
      Data = time.getDate() < 10 ? 0 + "" + time.getDate() : time.getDate(),
      hour = time.getHours() < 10 ? 0 + "" + time.getHours() : time.getHours(),
      Minutes =
        time.getMinutes() < 10 ? 0 + "" + time.getMinutes() : time.getMinutes(),
      Seconds =
        time.getSeconds() < 10 ? 0 + "" + time.getSeconds() : time.getSeconds();
    Month < 10 ? (Month = 0 + "" + Month) : "";
    return `${Year}-${Month}-${Data} ${hour}:${Minutes}:${Seconds}`;
  }

  /**
   * @param t格式化的时间戳
   * @return 2021-12-12 12:12:12 如果t没传返回当前的时间
   **/
  sjhbert(t, type) {
    let time = new Date();
    time.setTime(t);
    let Year = time.getFullYear(),
      Month = time.getMonth() + 1,
      Data = time.getDate() < 10 ? 0 + "" + time.getDate() : time.getDate(),
      hour = time.getHours() < 10 ? 0 + "" + time.getHours() : time.getHours(),
      Minutes =
        time.getMinutes() < 10 ? 0 + "" + time.getMinutes() : time.getMinutes(),
      Seconds =
        time.getSeconds() < 10 ? 0 + "" + time.getSeconds() : time.getSeconds();
    Month < 10 ? (Month = 0 + "" + Month) : "";

    return `${Year}-${Month}-${Data} ${type == 0 ? "00:00:00" : "23:59:59"}`;
  }

  analysisToken(token) {
    return new Promise((resolve, reject) => {
      let result = null;
      try {
        let { data, ctime, expiresIn } = jwt.verify(
          token,
          this.config("secretKeytoken")
        );
        let nowTime = new Date().getTime();
        if (nowTime - ctime < expiresIn) {
          result = data;
        }
      } catch (error) {}
      if (result) {
        resolve(result);
      } else {
        resolve("");
      }
    });
  }

  __call() {}
};
